package com.fudong.floatwindows;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.TimerTask;

public class FloatWinfowServices extends Service {

    private int textColor = 0xff000000;
    TimerTask task = null;
    private static final String TAG = "FloatWinfow";
    private WindowManager winManager;
    private WindowManager.LayoutParams wmParams;
    private LayoutInflater inflater;
    //浮动布局
    private View mFloatingLayout;
    private BaseCustomTextView remoteContent;
    private ImageButton closeButton;
    private ImageButton returnButton;
    private ImageButton enlargeButton;
    private ImageButton moveButton;
    private ImageButton rotateButton;
    private ImageButton imageButton5;
    private MyBinder binder;
    private int width = 800;
    private int height = 800;
    private int screenWidth = 0;
    private int screenHeight = 0;

    private int winMinWidth = 0;
    private int winMinHeight = 0;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        //悬浮框点击事件的处理
        init();
        return binder;
    }

    private void init(){
        initWindow();
        initFloating();
    }
    public class MyBinder extends Binder {

        public FloatWinfowServices getService() {
            return FloatWinfowServices.this;
        }

        @Override
        protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags) throws RemoteException {
            Log.e(TAG, "onTransact: "+code);
            if(code == 1){
                String dataStr = data.readString();
                Log.e(TAG, "onTransact: 重新加载");
                width = 400;
                height = 400;
                init();
            }

            return super.onTransact(code, data, reply, flags);

        }

        public void setText(String text,int textSize,int textColor){
            if(remoteContent != null){
                remoteContent.setText(text);
                remoteContent.setTextSize(textSize);
                remoteContent.setScrollSpeed(textColor);
//                remoteContent.setText(text,textSize,textColor);
            }
        }

        public void startScroll(){
            if(remoteContent != null){
                remoteContent.startAutoScroll();
            }
        }

        public void stopScroll(){
            if(remoteContent != null){
                remoteContent.stopAutoScroll();
            }
        }

        public void setScrollSpeed(int speed){
            if(remoteContent != null){
                remoteContent.setScrollSpeed(speed);
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        binder = new MyBinder();
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        DisplayMetrics dm = new DisplayMetrics();
        winManager.getDefaultDisplay().getMetrics(dm);
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            if(screenHeight - 210 < height){
                width = width * (screenHeight - 210)/height;
                height = screenHeight - 210;
                if(width < winMinWidth){
                    width = winMinWidth;
                }
            }
            updateWindow(width,height);
        }else{
            Log.e(TAG, "onConfigurationChanged: 竖屏 " );
            if(screenWidth - 210 < width){
                height = height * (screenWidth - 210)/width;
                width = screenWidth - 210;
                if(height < winMinHeight){
                    height = winMinHeight;
                }
            }
            updateWindow(width,height);
        }
    }

    private boolean isHorizontal = false;

    /**
     * 切换到横向
     */
    public void switch2Horizontal(){
        isHorizontal = true;
//        float step = remoteContent.getStep();
        float textSize = remoteContent.getTextSize();
        int textColor = remoteContent.getTextColor();
        String text = remoteContent.getText();
        int speed = remoteContent.getScrollSpeed();
        remoteContent.stopAutoScroll();
        winManager.removeView(mFloatingLayout);
        mFloatingLayout = inflater.inflate(R.layout.remoteview_h, null);
        //需要重新初始化参数
        winManager.addView(mFloatingLayout,wmParams);
        initFloating();
        Log.e("yqy","height = " + height + " width " + width + "  wmParams.width = " + wmParams.width + " wmParams.height = " + wmParams.height );
        remoteContent.setScrollSpeed(speed);
        remoteContent.setText(text);
        remoteContent.setTextColor(textColor);
        remoteContent.setTextSize(textSize);
        //        remoteContent.setRotate(90,wmParams.width,wmParams.height);
    }

    /**
     * 切换成纵向模式
     */
    public void switch2Vertical(){
        isHorizontal = false;
//        float step = remoteContent.getStep();
        float textSize = remoteContent.getTextSize();
        int textColor = remoteContent.getTextColor();
        String text = remoteContent.getText();
        int speed = remoteContent.getScrollSpeed();
        remoteContent.stopAutoScroll();
        winManager.removeView(mFloatingLayout);
        mFloatingLayout = inflater.inflate(R.layout.remoteview, null);
        winManager.addView(mFloatingLayout,wmParams);
        initFloating();
//        remoteContent.setStep(step);
        remoteContent.setScrollSpeed(speed);
        remoteContent.setText(text);
        remoteContent.setTextColor(textColor);
        remoteContent.setTextSize(textSize);
//        remoteContent.setText(text,textSize,textColor);
    }
    /**
     * 悬浮窗点击事件
     */
    private void initFloating() {

        winMinWidth = dip2px(45) * 4 + 1;
        winMinHeight = dip2px(45) * 2 + dip2px(20);
        imageButton5 = mFloatingLayout.findViewById(R.id.imageButton5);
        returnButton = mFloatingLayout.findViewById(R.id.remote_return);
        closeButton = mFloatingLayout.findViewById(R.id.remote_close);
        remoteContent = mFloatingLayout.findViewById(R.id.remote_content);
        moveButton = mFloatingLayout.findViewById(R.id.remote_move);
        enlargeButton  = mFloatingLayout.findViewById(R.id.remote_enlarge);
//        remoteContent.setWidth(wmParams.width);
//        remoteContent.setHeight(wmParams.height);
        width = wmParams.width;
        height = wmParams.height;
        remoteContent.setTextColor(textColor);
        wmParams.x = (screenWidth - wmParams.width)/2;
        winManager.updateViewLayout(mFloatingLayout,wmParams);
        //返回app事件
        returnButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(FloatWinfowServices.this, FudongModule.ac.getClass());
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
            }
        });
        //关闭事件
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeWindow();
            }
        });
        //触摸事件，设置悬浮框可拖动
        moveButton.setOnTouchListener(new FloatingListener());
        //触摸事件，设置悬浮框可缩放
        enlargeButton.setOnTouchListener(new EnlargeListener());

        mFloatingLayout.findViewById(R.id.remote_xuanzhuan).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isHorizontal){
                    switch2Vertical();
                }else{
                    switch2Horizontal();
                }

            }
        });
        imageButton5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(remoteContent.isAutoScroll()){
                    remoteContent.stopAutoScroll();
                    imageButton5.setImageResource(R.mipmap.video);
                }else{
                    remoteContent.startAutoScroll();
                    imageButton5.setImageResource(R.mipmap.play);
                }
            }
        });
    }


    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private int mTouchStartX, mTouchStartY, mTouchCurrentX, mTouchCurrentY;
    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private int mStartX, mStartY, mStopX, mStopY;
    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private boolean isMove;
    private int startWmParamsX;
    private int startWmParamsY;
    private class FloatingListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    isMove = false;
                    mTouchStartX = (int) event.getRawX();
                    mTouchStartY = (int) event.getRawY();
                    mStartX = (int) event.getX();
                    mStartY = (int) event.getY();
                    startWmParamsX = wmParams.x;
                    startWmParamsY = wmParams.y;
                    break;
                case MotionEvent.ACTION_MOVE:
                    mTouchCurrentX = (int) event.getRawX();
                    mTouchCurrentY = (int) event.getRawY();
                    wmParams.x = startWmParamsX + mTouchCurrentX - mTouchStartX;
                    if(wmParams.x < 0){
                        wmParams.x = 0;
                    }else if(wmParams.x > screenWidth-mFloatingLayout.getWidth()){
                        wmParams.x = screenWidth-mFloatingLayout.getWidth();
                    }
                    wmParams.y = startWmParamsY + mTouchCurrentY - mTouchStartY;
                    if(wmParams.y < 130){
                        wmParams.y = 130;
                    }else if(wmParams.y > screenHeight-mFloatingLayout.getHeight()+130){
                        wmParams.y = screenHeight-mFloatingLayout.getHeight()+130;
                    }
                    winManager.updateViewLayout(mFloatingLayout, wmParams);
//                    mTouchStartX = mTouchCurrentX;
//                    mTouchStartY = mTouchCurrentY;
                    break;
                case MotionEvent.ACTION_UP:
                    mStopX = (int) event.getX();
                    mStopY = (int) event.getY();
                    if (Math.abs(mStartX - mStopX) >= 1 || Math.abs(mStartY - mStopY) >= 1) {
                        isMove = true;
                    }
                    break;
                default:
                    break;
            }

            //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
            return isMove;
        }
    }

    private int startWidth = 0;
    private int startHeight = 0;
    private class EnlargeListener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    isMove = false;
                    mTouchStartX = (int) event.getRawX();
                    mTouchStartY = (int) event.getRawY();
                    mStartX = (int) event.getX();
                    mStartY = (int) event.getY();
                    startWidth = width;
                    startHeight = height;
                    wmPhx = width + wmParams.x;
                    break;
                case MotionEvent.ACTION_MOVE:
                    if(isHorizontal){
                        initContentViewSizeHorizontal(event);
                    }else{
                        initContentViewSizeVertical(event);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    mStopX = (int) event.getX();
                    mStopY = (int) event.getY();
                    if (Math.abs(mStartX - mStopX) >= 1 || Math.abs(mStartY - mStopY) >= 1) {
                        isMove = true;
                    }
                    if(isHorizontal){
                        initContentViewSizeHorizontal(event);
                    }else{
                        initContentViewSizeVertical(event);
                    }
                    break;
                default:
                    break;
            }

            //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
            return isMove;
        }
    }

    private void initContentViewSizeVertical(MotionEvent event){

        mTouchCurrentX = (int) event.getRawX();
        mTouchCurrentY = (int) event.getRawY();
        width = startWidth + (mTouchCurrentX - mTouchStartX);
        if(width<winMinWidth){
            width = winMinWidth;
            Log.e("yqy","width = " + width + " winMinWidth = " + winMinWidth);
        }else if(width+wmParams.x>screenWidth){
            width = screenWidth - wmParams.x;
            if(width < winMinWidth){
                width = winMinWidth;
            }
            Log.e("yqy","width = " + width + " winMinWidth = " + winMinWidth);
        }
        height = startHeight + (mTouchCurrentY - mTouchStartY);
        if(height<winMinHeight){
            height = winMinHeight;
        }else if(height+wmParams.y>screenHeight - 10){
            height = screenHeight-wmParams.y - 10;
            if(height < winMinHeight){
                height = winMinHeight;
            }
        }
        Log.e("yqy","screenHeight = " + screenHeight + " wmParams.y = " + wmParams.y);
        Log.e("yqy","height = " + height + " winMinHeight = " + winMinHeight);
        wmParams.width = width;
        wmParams.height = height;
        winManager.updateViewLayout(mFloatingLayout, wmParams);
//        remoteContent.setWidth(width);
//        remoteContent.setHeight(height);
    }

    private int wmPhx = 0;
    private void initContentViewSizeHorizontal(MotionEvent event){
        Log.e("yqy","initContentViewSizeHorizontal()");
        mTouchCurrentX = (int) event.getRawX();
        mTouchCurrentY = (int) event.getRawY();
        width = startWidth - (mTouchCurrentX - mTouchStartX);
        if(width<winMinHeight){
            width = winMinHeight;
        }else if(width+wmParams.x>screenWidth){
            width = screenWidth - wmParams.x;
            if(width < winMinHeight){
                width = winMinHeight;
            }
        }
        height = startHeight + (mTouchCurrentY - mTouchStartY);
        if(height<winMinWidth){
            height = winMinWidth;
        }else if(height+wmParams.y>screenHeight - 10){
            height = screenHeight-wmParams.y - 10;
            if(height < winMinWidth){
                height = winMinWidth;
            }
        }
        wmParams.x = (int) (wmPhx - width);
        winManager.updateViewLayout(mFloatingLayout, wmParams);
        wmParams.width = width;
        wmParams.height = height;
        winManager.updateViewLayout(mFloatingLayout, wmParams);
        remoteContent.requestLayout();
//        remoteContent.setWidth(width);
//        remoteContent.setHeight(height);
//        remoteContent.setRotate(90,wmParams.width,wmParams.height);
    }

    /**
     * 初始化窗口
     */
    private void initWindow() {
        winManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        //设置好悬浮窗的参数
        wmParams = getParams();
        // 悬浮窗默认显示以左上角为起始坐标
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        //悬浮窗的开始位置，因为设置的是从左上角开始，所以屏幕左上角是x=0;y=0
        DisplayMetrics dm = new DisplayMetrics();
        winManager.getDefaultDisplay().getMetrics(dm);
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;
        wmParams.x = (screenWidth - dm.widthPixels + 420)/2;
        wmParams.y = 210;
        // 不设置这个弹出框的透明遮罩显示为黑色
        wmParams.format = PixelFormat.TRANSLUCENT;
        //得到容器，通过这个inflater来获得悬浮窗控件
        inflater = LayoutInflater.from(getApplicationContext());
        // 获取浮动窗口视图所在布局
        mFloatingLayout = inflater.inflate(R.layout.remoteview, null);
        // 添加悬浮窗的视图
        wmParams.height = dm.heightPixels/2;
        wmParams.width = dm.widthPixels - 420;
        winManager.addView(mFloatingLayout, wmParams);
        if(task == null){
            task = new TimerTask() {
                @Override
                public void run() {
                    // 逻辑处理
                }
            };
        }

    }

    /**
     * 更新窗口
     */
    private void updateWindow(int width,int height){
        winManager.removeView(mFloatingLayout);
        //设置好悬浮窗的参数
        wmParams = getParams();
        // 悬浮窗默认显示以左上角为起始坐标
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        //悬浮窗的开始位置，因为设置的是从左上角开始，所以屏幕左上角是x=0;y=0
        Log.e("YQY","screenHeight = " + screenHeight + " screenWidth = " + screenWidth);
        // 不设置这个弹出框的透明遮罩显示为黑色
        wmParams.format = PixelFormat.TRANSLUCENT;
        //得到容器，通过这个inflater来获得悬浮窗控件
        wmParams.height = height;
        wmParams.width = width;
        wmParams.x = (screenWidth - width)/2;
        wmParams.y = (screenHeight - height)/2;
        winManager.addView(mFloatingLayout,wmParams);
    }

    private WindowManager.LayoutParams getParams() {
        wmParams = new WindowManager.LayoutParams();
        //设置window type 下面变量2002是在屏幕区域显示，2003则可以显示在状态栏之上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        //设置可以显示在状态栏上
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        return wmParams;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 关闭视图方法
     */
    private void closeWindow(){
        if(mFloatingLayout == null || mFloatingLayout.getParent() == null){
            return;
        }
        winManager.removeView(mFloatingLayout);
        if(task!=null){
            task.cancel();
        }
        if(mOnServiceListener != null){
            mOnServiceListener.onClosed();
        }
        if(remoteContent != null){
            remoteContent.stopAutoScroll();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWindow();
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public int px2dip(float pxValue) {
        final float scale = getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dip2px(float dpValue) {
        final float scale = getApplicationContext().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private OnServiceListener mOnServiceListener;
    public interface OnServiceListener{
        void onClosed();
    }

    public void setOnServiceListener(OnServiceListener mOnServiceListener){
        this.mOnServiceListener = mOnServiceListener;
    }
}